package com.yl.qunai_kotlin

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.yl.common.base.BaseActivity
import com.yl.common.util.ToastUtil
import com.yl.conference.fragment.ConferenceFragment
import com.yl.home.fragment.HomeFragment
import com.yl.message.fragment.MessageFragment
import com.yl.mine.fragment.MineFragment
import com.yl.qunai_kotlin.databinding.ActivityMainBinding

class MainActivity : BaseActivity<ActivityMainBinding>() {

    private lateinit var fragmentList: MutableList<Fragment>
    private var oldFragmentIndex: Int = 0


    private fun initFragmentList() {
        fragmentList = mutableListOf(
            HomeFragment(),
            ConferenceFragment(),
            MessageFragment(),
            MineFragment()
        )
    }

    private fun initNavigation() {
        mBind.bnv.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.item_home -> switchFragment(0)
                R.id.item_discover -> switchFragment(1)
                R.id.item_hot -> switchFragment(2)
                R.id.item_mine -> switchFragment(3)
            }
            true
        }
    }


    private fun switchFragment(position: Int) {
        val ft = supportFragmentManager.beginTransaction()
        val targetFragment = fragmentList[position]
       // hintFragment(ft)
        val oldFragment = fragmentList[oldFragmentIndex]
        oldFragmentIndex = position

        if (oldFragment.isAdded) {
            ft.hide(oldFragment)
        }
        if (!targetFragment.isAdded) {
            ft.add(R.id.f_content, targetFragment)
        }

        ft.show(targetFragment).commitAllowingStateLoss()
    }

    private fun hintFragment(ft: FragmentTransaction) {
        val fragments = supportFragmentManager.fragments
        for (fragment in fragments) {
            ft.remove(fragment)
        }
    }

    private var exitTime: Long = 0
    override fun onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            ToastUtil.showMsg("再按一次退出")
            exitTime = System.currentTimeMillis()
        } else {
            super.onBackPressed()
        }
    }

    override fun getLayoutID(): Int = R.layout.activity_main

    override fun init() {
        initFragmentList()
        initNavigation()
        switchFragment(0)
    }
}